/**
 * utility 公共工具类
 */
import axios from 'axios'
const nowEnv = process.env.NODE_ENV
const KYB_MIN_NUM = 1e-10
const webconfig = {
  // apiAddress: 'api/ccservice',
  // gatewayApiAdress: 'newgateway/api-gateway',
  // devApiAddress: 'https://c1ccservice.kjtpay.com/ccservice',
  devGatewayAddress: `https://${
    import.meta.MODE === 'testc1' ? 'c1' : 'c2'
  }api-gateway.kjtpay.com/api-gateway`,
  mappurl: 'common/getRandomKey',
}
export const __DEV__ = nowEnv === 'development'
/**
 * 查询url参数对象
 * @returns 参数对象
 */
export function getSearchParams() {
  const args = {}
  const query = window.location.search.substring(1)
  const pairs = query.split('&')
  for (let i = 0; i < pairs.length; i += 1) {
    const pos = pairs[i].indexOf('=')
    if (pos !== -1) {
      const name = pairs[i].substring(0, pos)
      let value = pairs[i].substring(pos + 1)
      value = decodeURIComponent(value)
      args[name] = value
    }
  }
  return args
}

export function getAxioCommonBody() {
  let token = sessionStorage.getItem('token') || getSearchParams().token,
    tokenType = 'UNIONMA_TOKEN'
  if (location.href.toLowerCase().indexOf('/cross/') > -1) {
    token = sessionStorage.getItem('token')
    tokenType = 'UNIONMA_TOKEN'
  } else if (
    location.href.toLowerCase().indexOf('/bizfacescanmanage/') > -1 ||
    location.href.toLowerCase().indexOf('/certagain/') > -1 ||
    location.href.toLowerCase().indexOf('/orderindex') > -1 ||
    location.href.toLowerCase().indexOf('/myauditstatus') > -1 ||
    location.href.toLowerCase().indexOf('/bdmanagelist') > -1 ||
    location.href.toLowerCase().indexOf('/signature/') > -1
  ) {
    token = userInfoDevice.kjtToken ? userInfoDevice.kjtToken : userInfo.h5Token
    tokenType = 'LOGIN-TOKEN'
  } else if (location.href.toLowerCase().indexOf('/plateform/') > -1) {
    token = userInfo.token
    tokenType = 'SSO-AUTH'
  }
  return {
    bizContent: '',
    loginAuthInfo: {
      isEnt: '',
      loginToken: token,
      loginTokenType: tokenType,
      operatorId: '',
      operatorName: '',
      partnerId: '',
      institution: 'wechat',
      bizType: 'fps',
    },
    requestNo: `requestno${new Date().getTime()}${parseInt(
      Math.random() * 1000000
    )}`,
    sarsTokenId: window.blackbox ? window.blackbox : '',
    service: '',
    sign: '1245',
    signType: 'AES',
    terminalInfo: {
      terminal: 'H5',
    },
    timestamp: new Date().getTime(),
    version: '1.0.0',
  }
}
function removeSuffix(str) {
  if (!str.includes('.')) return str
  return str.substring(0, str.lastIndexOf('.'))
}
/**
 * 图片上传
 */
export function uploadFileV2(paraFile) {
  let form = new FormData()
  let _gateway = getAxioCommonBody()
  form.append(
    'fileName',
    new Date().getTime() + '_' + removeSuffix(paraFile.name)
  )
  form.append('file', paraFile, paraFile.name)
  if (isNoNeedPreviewFile(paraFile.name)) {
    form.append('bizType', 'kyb')
  } else {
    form.append('bizType', 'kyb')
  }
  form.append('sysCode', 'cb_trade')
  form.append('requestBaseStr', JSON.stringify(_gateway))
  //文件上传
  return axios({
    baseURL: getGatewayDomain(),
    url: '/uploadFileV2', //TODO
    headers: { 'X-Requested-With': 'XMLHttpRequest' },
    method: 'post',
    data: form,
  })
}

const getGMMappUrl = () => {
  return `${getGatewayDomain()}/getRandomKeyGmH5`
}

const isInArray = (arr, str) => {
  //判断值在数组里存在
  let _isInArray = false
  if (arr && str && str.length > 0) {
    for (let i = 0; i < arr.length; i++) {
      if (arr[i] == str) {
        _isInArray = true
      }
    }
  }
  return _isInArray
}

const isNoNeedPreviewFile = (val) => {
  //pdf word excel 不需要预览
  let suffixArr = ['pdf', 'doc', 'docx', 'xls', 'xlsx'],
    fileName = val ? val : '',
    // suffix = val.substring(val.lastIndexOf(".")+1).toLowerCase();
    suffix = fileName.substring(fileName.lastIndexOf('.') + 1)
  return isInArray(suffixArr, suffix)
}
const getGatewayDomain = () => {
  var _domain = ''
  if (__DEV__) {
    _domain = webconfig.devGatewayAddress
  } else {
    _domain = import.meta.env.VITE_REQUEST_BASE_URL
  }
  return _domain
}
const getTargetByValue = (list, value) => {
  let target = {}
  if (list && list.length && value) {
    list.forEach((v) => {
      if (v.value.includes(',')) {
        if (v.value.split(',').includes(value)) {
          target = v
        }
      } else if (v.value === value) {
        target = v
      }
    })
  }
  return target
}

const getLabelByValue = (list, value) => {
  let obj = getTargetByValue(list, value)
  return obj.label
}

const getOssStaticDomain = () => {
  let ossDomain = 'https://c1-static.kjtpay.com',
    host = window.location.host
  if (host && host.indexOf('c1global') > -1) {
    ossDomain = 'https://c1-static.kjtpay.com'
  } else if (host && host.indexOf('c2global') > -1) {
    ossDomain = 'https://c1-static.kjtpay.com' //oss 测试2没有域名
  } else if (host && host.indexOf('zglobal') > -1) {
    ossDomain = 'https://zsc-static.kjtpay.com'
  } else if (host && host.indexOf('global') > -1) {
    ossDomain = 'https://sc-static.kjtpay.com'
  }
  return ossDomain
}

// 高精度对比，取第一个数 和后续数之和对比
const highPrecisionEqual = (...args) => {
  if (!args || args.length < 2) return false
  var _args = [...args]
  const firstValue = parseFloat(_args.shift())
  const sum = _args.reduce((s, v) => s + parseFloat(v), 0)
  return Math.abs(firstValue - sum) < KYB_MIN_NUM
}
//是否测试环境
const isTestEnv = () => {
  let isTest = true
  if (import.meta.env.VITE_BASE === '/prod') {
    isTest = false
  }
  return isTest
}
const getDateTime = () => {
  var date = new Date()
  var year = date.getFullYear()
  var month = date.getMonth() + 1
  var curDate = date.getDate()
  if (month >= 1 && month <= 9) {
    month = '0' + month
  }
  if (curDate >= 0 && curDate <= 9) {
    curDate = '0' + curDate
  }
  return `${year}-${month}-${curDate}`
}
const imgPreLoad = (url, id) => {
  if (!url) return
  return new Promise((resolve) => {
    const img = new Image()
    img.src = url
    img.onload = function () {
      img.width = '0'
      img.height = '0'
      img.style.display = 'none'
      img.id = id
      document.body.appendChild(img)
      resolve()
    }
  })
}
export default {
  clearCompany: function () {
    sessionStorage.removeItem('CompanyInfo')
  },
  getGMMappUrl,
  getSearchParams,
  isInArray,
  isNoNeedPreviewFile,
  uploadFileV2,
  getGatewayDomain,
  getTargetByValue,
  getLabelByValue,
  highPrecisionEqual,
  getOssStaticDomain,
  isTestEnv,
  getDateTime,
  imgPreLoad,
}
